package com.mk.service.web;

import act.controller.Controller;
import com.mk.domain.ZMembers;
import com.mk.enums.GlobalValues;
import com.mk.exception.UserException;
import com.mk.interceptor.ITranslate;
import com.mk.service.BasePaasService;
import org.osgl.mvc.annotation.GetAction;
import org.osgl.mvc.annotation.PutAction;
import org.osgl.mvc.annotation.With;
import org.osgl.util.S;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller("zMembers")
public class ZMembersService extends BaseWebService {
    @Inject
    private ZMembers.Mapper zMembersMapper;
    @Inject
    private BasePaasService basePaasService;

    /**
     * 更新我的手机号和我的邀请人信息
     * 注意:只有没绑定过手机号的用户才能绑定手机号,并填写推广人
     *
     */
    @PutAction("updateMyPid.json")
    @With({WbILogin.class, ITranslate.class})
    public Integer updateMyPid(String phone,String code,String refcode){
        basePaasService.validateCode(phone, code);
        ZMembers param = new ZMembers();
        param.setPhone(phone);
        Long count = zMembersMapper.templateCount(param);
        if(count>0){
            throw new UserException("该手机号已经注册,请更换手机号");
        }
        ZMembers members = new ZMembers();
        members.setMid(me.getMid());
        members.setPhone(phone);
        if(S.isNotBlank(refcode)){
            String pmid = zMembersMapper.createLambdaQuery().andEq(ZMembers::getRefcode, refcode).select(ZMembers::getMid).get(0).getMid();
            if(S.isNotBlank(pmid)){
                members.setPmid(pmid);
            }
        }
        return zMembersMapper.updateTemplateById(members);
    }

    /**
     * 更新账户认证信息
     */
    @PutAction("update.json")
    @With({WbILogin.class, ITranslate.class})
    public Integer updateMembers(ZMembers members){
        ZMembers member = zMembersMapper.single(me.getMid());
        if(S.isBlank(member.getStatus())||S.eq(GlobalValues.Z_MEM_STATE_2.value(),member.getStatus())){
            members.setMdate(me.getMdate());
            members.setStatus(GlobalValues.Z_MEM_STATE_0.value());
            return zMembersMapper.updateTemplateById(members);
        }else {
            throw new UserException("不能重新提交认证");
        }
    }


    @GetAction("myCustomer.json")
    @With(WbILogin.class)
    public List<Map<String,Object>> myCustomer(Integer curpage, Integer pagesize){
        List<Map<String,Object>> result = zMembersMapper.selectMyCustomer(me.getMid(),null,null,curpage*pagesize,pagesize);
        if(result!=null){
            return result;
        }
        return new ArrayList<>();
    }

    @GetAction("myCustomerCount.json")
    @With(WbILogin.class)
    public Integer myCustomerCout(Integer curpage, Integer pagesize){
        Integer result = zMembersMapper.selectMyCustomerCount(me.getMid(),null,null);
        return result;
    }
}
